import { jsPDF } from "jspdf";
import * as UTIF from "utif";
import { useDictionryStore } from "@/stores/modules/dictionary";

let initCount = 0;

/**
 * @param files 多个图片 File（支持 jpg/png）
 * @returns Promise<File> 合成后的 PDF 文件
 */
export const multiImagesToPDF = async (files: File[], uploadType: string | null): Promise<File> => {
  const pdf = new jsPDF();
  const pageWidth = pdf.internal.pageSize.getWidth();
  const store = useDictionryStore();

  for (let i = 0; i < files.length; i++) {
    const imgData = await fileToDataURL(files[i]);
    const imgSize = await getImageSize(imgData);

    const imgHeight = (imgSize.height * pageWidth) / imgSize.width;

    if (i > 0) pdf.addPage();

    pdf.addImage(imgData, files[i].type === "png" ? "PNG" : "JPEG", 0, 0, pageWidth, imgHeight);
  }

  const pdfBlob = pdf.output("blob");
  let curFileName = "";
  if (uploadType) {
    curFileName = `${store.strFileNameWithoutExt}-${initCount + 1}.pdf`;
    initCount += 1;
  } else {
    curFileName = `${store.strFileNameWithoutExt}.pdf`;
  }

  console.log("curFileName----1", curFileName);

  const pdfFile = new File([pdfBlob], `${curFileName}`, {
    type: "application/pdf"
  });

  return pdfFile;
};

// 把 File 转成 base64 dataURL
const fileToDataURL = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
};

// 获取图片宽高
const getImageSize = (src: string): Promise<{ width: number; height: number }> => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve({ width: img.width, height: img.height });
    img.onerror = reject;
    img.src = src;
  });
};

/**
 * 以下为图片file转tif文件
 */

// 文件转Image对象
const fileToImage = (file: File): Promise<HTMLImageElement> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      const img = new Image();
      img.onload = () => resolve(img);
      img.onerror = reject;
      img.src = reader.result as string;
    };
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
};

// 把图片转成 RGB Uint8Array（去除 Alpha）
const imageToRGBA = (img: HTMLImageElement): any => {
  const canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  const ctx = canvas.getContext("2d")!;
  ctx.drawImage(img, 0, 0);
  const imgData = ctx.getImageData(0, 0, img.width, img.height);
  return imgData.data;
};

export async function mergeImagesToTIF(files: any[]): Promise<any> {
  const tiffIFDs: any = [];

  for (const file of files) {
    const img = await fileToImage(file);
    const rgba = imageToRGBA(img); // Uint8ClampedArray

    const width = img.width;
    const height = img.height;
    // 修改后的 metadata，只使用 RGB 相关
    const metadata = {
      t256: [width],
      t257: [height],
      t278: [height],
      t279: [width * height * 3]
    } as any;
    const tiffData = UTIF.encodeImage(rgba, width, height, metadata);
    const blob = new Blob([tiffData], { type: "image/tiff" });
    tiffIFDs.push(new File([blob], `SCAN_${Date.now()}.tif`, { type: "image/tiff" }));
    if (tiffIFDs.length === files.length) {
      return tiffIFDs;
    }
  }
}
